package cn.ehanghai.iot.back.controller;

import cn.ehanghai.iot.back.domain.UserInfo;
import cn.ehanghai.iot.back.service.UserInfoService;
import cn.ehanghai.iot.config.DefineUtil;
import cn.ehanghai.iot.config.WechatAccountConfig;
import cn.ehanghai.iot.utils.*;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * 微信公众号开发
 * Created by 廖师兄
 * 2017-07-03 00:50
 */
@RestController
@RequestMapping("/weixin")
@Slf4j
public class WeixinController {

    public static String URL = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";

    @Autowired
    private WechatAccountConfig wechatAccountConfig;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private RedisTemplate<String,String> template;

    @GetMapping("/auth")
    public String auth(@RequestParam("code") String code) {
        log.info("进入auth方法。。。");
        log.info("code={}", code);

       String appId= wechatAccountConfig.getMpAppId();
       String secret=wechatAccountConfig.getMpAppSecret();
//        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appId+"&secret="+secret+"&code=" + code + "&grant_type=authorization_code";
//        RestTemplate restTemplate = new RestTemplate();
//        String response = restTemplate.getForObject(url, String.class);
//        log.info("response={}", response);
        return code;
    }

    /**
     * 验证token
     */
    @RequestMapping(value = "/wx",method = RequestMethod.GET)
    public void wx(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        PrintWriter out = response.getWriter();
        if (SignUtil.checkSignature(signature, timestamp, nonce)) {
            // 如果校验成功，将得到的随机字符串原路返回
            out.print(echostr);
        }
    }


    @RequestMapping(value = "/wx",method = RequestMethod.POST)
    public void processMsg(HttpServletRequest request,HttpServletResponse response) throws WxErrorException {
        System.out.println("进入公众号开发");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = null;
        Map<String,String> map = MessageUtil.xmlToMap(request);
        String ToUserName = map.get("ToUserName");
        String FromUserName = map.get("FromUserName");
        String MsgType = map.get("MsgType");
        String eventType = map.get("Event");
        UserInfo userInfo=userInfoService.getUserInfoByOpenId(FromUserName);
        String message = "";
        if(TextMessageUtil.MSGTYPE_EVENT.equals(MsgType)){
            //如果是关注事件
            if(TextMessageUtil.MESSAGE_SUBSCIBE.equals(eventType)){
                //Todo 保存用户信息
                if(userInfo==null){
                    userInfo=new UserInfo(FromUserName,"0",DefineUtil.FOLLOW_SATATUS);
                    userInfo.setStatus(DefineUtil.UNCHECK_STATUS);
                    userInfo.setInviteCount(0);
                    userInfoService.saveOrUpdate(userInfo);
                }else{
                    userInfo.setFollow(DefineUtil.FOLLOW_SATATUS);
                    userInfoService.saveOrUpdate(userInfo);
                }
                message=TextMessageUtil.subscribeForText(FromUserName,ToUserName);
            }
            else if(TextMessageUtil.MESSAGE_UNSUBSCIBE.equals(eventType)){
                //如果是取消关注
                if(userInfo!=null) {
                    userInfo.setFollow(DefineUtil.UNFOLLOW_SATATUS);
                    userInfoService.saveOrUpdate(userInfo);
                }
                message=TextMessageUtil.unsubscribe(FromUserName,ToUserName);
            }
        }else{
            switch (MsgType){
                case "text":{//文本消息
                    String content = map.get("Content");
                    if(content.equals("祝福祖国")){
                        content=TextMessageUtil.MESSAGE_CONTENT;
                    }else{
                        content = "您发的消息内容是:"+content+"";
                    }
                    message = TextMessageUtil.initMessage(FromUserName, ToUserName,content);
                }
                default:
                    break;
            }
        }
//        if("text".equals(MsgType)){
//            if("1".equals(Content)){
//                TextMessageUtil textMessage = new TextMessageUtil();
//                String content="欢迎关注海上通";
//                message = textMessage.initMessage(FromUserName, ToUserName,content);
//            }
//        }
        try {
            out = response.getWriter();
            out.write(message);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        out.close();
    }
//
//    /**
//     * 获取accessToken
//     * @return
//     * @throws WxErrorException
//     */
//    public  String getAccessToken() throws WxErrorException {
//        ValueOperations<String, String> forValue = template.opsForValue();
//        String accessToken = forValue.get("access_token_wx");
//        if(StringUtils.isEmpty(accessToken)){
//            String tokenUrl="https://api.weixin.qq.com/cgi-bin/token";
//            String param="grant_type=client_credential&appid="+wechatAccountConfig.getMpAppId()+"&secret="+wechatAccountConfig.getMpAppSecret()+"";
//            String result= HttpUitl.sendGet(tokenUrl,param);
//            JSONObject json = JSONObject.fromObject(result);
//            accessToken= (String) json.get("access_token");
//            //设置过期事件
//            template.opsForValue().set("access_token_wx", accessToken, 7000, TimeUnit.SECONDS);
//        }
//        return accessToken;
//    }
//
//    /**
//     * 获取用户信息
//     * @param openId
//     * @param accessToken
//     * @return
//     * @throws WxErrorException
//     */
//    public void getUserInfo(String openId,String accessToken) throws WxErrorException {
////        WxMpOAuth2AccessToken wxMpOAuth2AccessToken=new WxMpOAuth2AccessToken();
////        wxMpOAuth2AccessToken.setAccessToken(accessToken);
////        wxMpOAuth2AccessToken.setOpenId(openId);
////        WxMpUser wxMpUser=wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken,"zh_CN");
////        return wxMpUser;
//          String userUrl="https://api.weixin.qq.com/sns/userinfo";
//          String param="access_token="+accessToken+"&openid="+openId+"&lang=zh_CN";
//          String result= HttpUitl.sendGet(userUrl,param);
//          System.out.println(result);
//    }
//

}
